package org.meow.config;

import lombok.extern.slf4j.Slf4j;
import org.meow.interception.JwtAdminItcpt;
import org.meow.interception.JwtCommonItcpt;
import org.meow.json.JacksonObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

import java.util.List;

/**
 * &#064;Date: 24/04/22-17:37
 * &#064;Description:
 */
@Configuration
@Slf4j
public class WebMvcCfg extends WebMvcConfigurationSupport {

  @Autowired
  private JwtAdminItcpt  jwtAdminItcpt;
  @Autowired
  private JwtCommonItcpt jwtCommonItcpt;

  protected void addInterceptors(InterceptorRegistry registry) {
    log.info("注册自定义拦截器");
    registry
        .addInterceptor(jwtAdminItcpt)
        .addPathPatterns("/admin/**");
    registry
        .addInterceptor(jwtCommonItcpt)
        .addPathPatterns("/**")
        .excludePathPatterns("/v3/api-docs/**") // TODO: delete doc api
        .excludePathPatterns("/doc.html")
        .excludePathPatterns("/webjars/**")
        .excludePathPatterns("/admin/**")
        .excludePathPatterns("/user/login")
        .excludePathPatterns("/api/**");
  }


  @Override
  public void addCorsMappings(CorsRegistry registry) {
    registry.addMapping("/**")
            .allowedOrigins("http://localhost:5173")  // TODO: 改变域
            .allowedMethods("GET", "POST", "PUT", "DELETE")
            .allowedHeaders("*")
            .allowCredentials(true)
            .maxAge(3600);
  }

  protected void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/doc.html")
            .addResourceLocations("classpath:/META-INF/resources/");
    registry.addResourceHandler("/webjars/**")
            .addResourceLocations("classpath:/META-INF/resources/webjars/");
  }

  @Override
  protected void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
    MappingJackson2HttpMessageConverter jackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
    jackson2HttpMessageConverter.setObjectMapper(new JacksonObjectMapper());
    converters.add(converters.size() - 1, jackson2HttpMessageConverter);
    super.extendMessageConverters(converters);
  }


}
